/* global window */
/* global document */
/* global location */
import {routerRedux} from 'dva/router'
import {parse} from 'qs'
import config from 'config'
import {EnumRoleType} from 'enums'
import {query, logout, isLoginUser} from 'services/app'
import * as menusService from 'services/menus'
import queryString from 'query-string'

const {prefix} = config
const loginUrl = encodeURIComponent(window.location.href);

export default {
    namespace : 'app',
    state : {
        user: {},
        permissions: {
            visit: []
        },
        menu: [
            {
                id: 1,
                icon: 'laptop',
                name: '报表配置',
                router: '/reports'
            }
        ],
        menuPopoverVisible: false,
        siderFold: window
            .localStorage
            .getItem(`${prefix}siderFold`) === 'true',
        darkTheme: window
            .localStorage
            .getItem(`${prefix}darkTheme`) === 'true',
        isNavbar: document.body.clientWidth < 769,
        navOpenKeys: JSON.parse(window.localStorage.getItem(`${prefix}navOpenKeys`)) || [],
        locationPathname: '',
        locationQuery: {}
    },
    subscriptions : {

        setupHistory({dispatch, history}) {
            history.listen((location) => {
                dispatch({
                    type: 'updateState',
                    payload: {
                        locationPathname: location.pathname,
                        locationQuery: queryString.parse(location.search)
                    }
                })
            })
        },

        setup({dispatch}) {
            dispatch({type: 'initApp'})
            let tid
            window.onresize = () => {
                clearTimeout(tid)
                tid = setTimeout(() => {
                    dispatch({type: 'changeNavbar'})
                }, 300)
            }
        }
    },
    effects : {
        * initApp({
            payload
        }, {call, put, select}) {
            const {result} = yield call(isLoginUser, payload)
            const {locationPathname} = yield select(_ => _.app)
            // if (result.name == 'anonymous') {
            //     window.location.href = `/security/auth/login?returnUrl=${loginUrl}`;
            //     return;
            // }
            const {list} = yield call(menusService.query)
            yield put({
                type: 'updateState',
                payload: {
                    user: result,
                    menu: list
                }
            });
        },

        * logout({
            payload
        }, {call, put}) {
            const data = yield call(logout, parse(payload))
            if (data.success) {
                yield put({type: 'query'})
            } else {
                throw(data)
            }
        },

        * changeNavbar(action, {put, select}) {
            const {app} = yield(select(_ => _))
            const isNavbar = document.body.clientWidth < 769
            if (isNavbar !== app.isNavbar) {
                yield put({type: 'handleNavbar', payload: isNavbar})
            }
        }
    },
    reducers : {
        updateState(state, {payload}) {
            return {
                ...state,
                ...payload
            }
        },

        switchSider(state) {
            window
                .localStorage
                .setItem(`${prefix}siderFold`, !state.siderFold)
            return {
                ...state,
                siderFold: !state.siderFold
            }
        },

        switchTheme(state) {
            window
                .localStorage
                .setItem(`${prefix}darkTheme`, !state.darkTheme)
            return {
                ...state,
                darkTheme: !state.darkTheme
            }
        },

        switchMenuPopver(state) {
            return {
                ...state,
                menuPopoverVisible: !state.menuPopoverVisible
            }
        },

        handleNavbar(state, {payload}) {
            return {
                ...state,
                isNavbar: payload
            }
        },

        handleNavOpenKeys(state, {payload: navOpenKeys}) {
            return {
                ...state,
                ...navOpenKeys
            }
        }
    }
}
